package edu.uoc.tdp.pac4.server;

import edu.uoc.tdp.pac4.EAssistencia;
import edu.uoc.tdp.pac4.remote.Conexion;
import edu.uoc.tdp.pac4.remote.ConexionImpl;
import edu.uoc.tdp.pac4.remote.Estadisticas;
import edu.uoc.tdp.pac4.remote.EstadisticasImpl;
import edu.uoc.tdp.pac4.remote.GestAcademica;
import edu.uoc.tdp.pac4.remote.GestAcademicaImpl;
import edu.uoc.tdp.pac4.remote.GestorEstoc;
import edu.uoc.tdp.pac4.remote.GestorEstocImpl;
import edu.uoc.tdp.pac4.remote.Mantenimiento;
import edu.uoc.tdp.pac4.remote.MantenimientoImpl;
import edu.uoc.tdp.pac4.util.LanguageUtils;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

/**
 * Implementa el formulario correspondiente al servidor del proyecto.
 * 
 * @author eSupport Netbeans
 */
public class Servidor extends javax.swing.JFrame 
{
   // private final String urlRMI = "rmi://localhost/eAssistencia";
   private static LanguageUtils language = new LanguageUtils();
   
   // RMI registry
   private Registry registry;

   // Objetos remotos -> subsistemas
   private GestorEstoc stock;
   private Mantenimiento mant;
   private Estadisticas estad;
   private GestAcademica gacad;
   private Conexion conex;
   
   /**
    * Creates new form Servidor
    */
   public Servidor() 
   {
      initComponents();
      
      // Centra el formulario inicial
      this.setLocationRelativeTo(null);
      
      // Inicializa los elementos dependientes del idioma
      this.setTitle(language.getProperty("app.title") + " - " + language.getProperty("server.title"));
      cmdStart.setText(language.getProperty("form.main.cmdStart"));
      cmdStop.setText(language.getProperty("form.main.cmdStop"));
   }

   @Override
    public java.awt.Image getIconImage() {
        java.awt.Image retValue = java.awt.Toolkit.getDefaultToolkit().
                getImage(ClassLoader.getSystemResource("resources/eassistencia.gif"));     
        return retValue;
    }  
   /**
    * This method is called from within the constructor to initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is always
    * regenerated by the Form Editor.
    */
   @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        cmdStart = new javax.swing.JButton();
        cmdStop = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtConsole = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("UOC/TDP PAC3 - RMI Server");
        setIconImage(getIconImage());
        setResizable(false);

        cmdStart.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/cog_go.png"))); // NOI18N
        cmdStart.setText("Iniciar");
        cmdStart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdStartActionPerformed(evt);
            }
        });

        cmdStop.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/cog_delete.png"))); // NOI18N
        cmdStop.setText("Detener");
        cmdStop.setEnabled(false);
        cmdStop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdStopActionPerformed(evt);
            }
        });

        txtConsole.setEditable(false);
        txtConsole.setBackground(new java.awt.Color(0, 0, 0));
        txtConsole.setColumns(20);
        txtConsole.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N
        txtConsole.setForeground(new java.awt.Color(0, 255, 0));
        txtConsole.setRows(5);
        jScrollPane1.setViewportView(txtConsole);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 477, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(cmdStart, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmdStop, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmdStart)
                    .addComponent(cmdStop))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cmdStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdStartActionPerformed
      
      printToConsole(language.getProperty("console.starting"));

      try 
      {
                   
         cmdStart.setEnabled(false);
         
         registry = LocateRegistry.createRegistry(EAssistencia.RMI_PORT);    
         
         stock = new GestorEstocImpl();
         mant = new MantenimientoImpl();
         estad = new EstadisticasImpl();
         gacad = new GestAcademicaImpl();
         conex = new ConexionImpl();
         
         Naming.rebind(EAssistencia.RMI_URI_STOCK, stock);
         Naming.rebind(EAssistencia.RMI_URI_MANTENIMIENTO, mant);
         Naming.rebind(EAssistencia.RMI_URI_ESTADISTICAS, estad);
         Naming.rebind(EAssistencia.RMI_URI_GESTIONACAD, gacad);
         Naming.rebind(EAssistencia.RMI_URI_CONEXION, conex);
         
         printToConsole(language.getProperty("console.rmi_url") + ": " + EAssistencia.RMI_URI_BASE);
         printToConsole(language.getProperty("console.started"));

         cmdStop.setEnabled(true);
      }
      catch (RemoteException ex)
      {
         printToConsole(language.getProperty("rmi.errConnection") + ": " + ex.getMessage());
         printToConsole(language.getProperty("console.stopped"));
         
         stock = null;
         
         cmdStart.setEnabled(true);
         cmdStop.setEnabled(false);
      }
      catch (ClassNotFoundException ex)
      {
         printToConsole("== ERROR =======\nClassNotFoundException: " + ex.getMessage());
         printToConsole(language.getProperty("console.stopped"));
         
         stock = null;
         
         cmdStart.setEnabled(true);
         cmdStop.setEnabled(false);
      }
      catch (Exception ex) 
      {
         printToConsole("== ERROR =======\n" + ex.getMessage());
         printToConsole(language.getProperty("console.stopped"));
         
         stock = null;
         
         cmdStart.setEnabled(true);
         cmdStop.setEnabled(false);
      }
    }//GEN-LAST:event_cmdStartActionPerformed

   private void cmdStopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdStopActionPerformed
      
      try {            
          
            Naming.unbind(EAssistencia.RMI_URI_CONEXION);                        
            Naming.unbind(EAssistencia.RMI_URI_ESTADISTICAS);            
            Naming.unbind(EAssistencia.RMI_URI_MANTENIMIENTO);            
            Naming.unbind(EAssistencia.RMI_URI_GESTIONACAD);            
            Naming.unbind(EAssistencia.RMI_URI_STOCK);             
            UnicastRemoteObject.unexportObject(stock, true);
            UnicastRemoteObject.unexportObject(mant, true);
            UnicastRemoteObject.unexportObject(estad, true);
            UnicastRemoteObject.unexportObject(gacad, true);
            UnicastRemoteObject.unexportObject(conex, true);
            UnicastRemoteObject.unexportObject(registry, true);
            
            registry = null;
      }
      catch(RemoteException ex)
      {   
          
        printToConsole(language.getProperty("rmi.errConnection") + ": " + ex.getMessage());
       
      }      
      catch(NotBoundException ex)
      {        
          
        printToConsole("== ERROR =======\nNotBoundException: " + ex.getMessage());
               
      }catch(Exception ex)
      {
          
        printToConsole("== ERROR =======\n" + ex.getMessage());        
        
      }
      finally 
      {
        cmdStop.setEnabled(false);     
        stock = null;
        mant = null;
        estad = null;
        gacad = null;
        conex = null;
        registry = null;
        printToConsole(language.getProperty("console.stopped"));
        cmdStart.setEnabled(true);
      }                   
            
      
   }//GEN-LAST:event_cmdStopActionPerformed

   /**
    * @param args the command line arguments
    */
   public static void main(String args[]) 
   {
      /* Set the Nimbus look and feel */
      //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
       * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
       */
      try {
         for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
               javax.swing.UIManager.setLookAndFeel(info.getClassName());
               break;
            }
         }
      } catch (ClassNotFoundException ex) {
         java.util.logging.Logger.getLogger(Servidor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
      } catch (InstantiationException ex) {
         java.util.logging.Logger.getLogger(Servidor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
      } catch (IllegalAccessException ex) {
         java.util.logging.Logger.getLogger(Servidor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
      } catch (javax.swing.UnsupportedLookAndFeelException ex) {
         java.util.logging.Logger.getLogger(Servidor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
      }
      //</editor-fold>

      /* Create and display the form */
      java.awt.EventQueue.invokeLater(new Runnable() {
         @Override
         public void run() {
            new Servidor().setVisible(true);
         }
      });
   }
   
   private void printToConsole(String text)
   {
      String consoleTxt = txtConsole.getText() + "\n";
      txtConsole.setText(consoleTxt + "> " + text);
   }
   
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cmdStart;
    private javax.swing.JButton cmdStop;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea txtConsole;
    // End of variables declaration//GEN-END:variables
}
